package com.example.testapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class MyView extends View {

    // 默认控件宽高
    private static final int MY_VIEW_WIDTH = 500;
    private static final int MY_VIEW_HEIGHT = 500;
    // 声明画笔
    private Paint mPaint;

    public MyView(Context context){
        super(context);
        // 初始化画笔
        init();
    }
  // 初始化相关控件
    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    //测量并设置控件大小
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = measureDimension(MY_VIEW_WIDTH,widthMeasureSpec);
        int height = measureDimension(MY_VIEW_HEIGHT,heightMeasureSpec);
        // 设置测量结果
        setMeasuredDimension(width,height);
    }

    // 测量尺寸
    protected int measureDimension(int defaultSize,int measureSpec){
        int result = defaultSize;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        //1. layout给出了确定的值，比如：100dp
        //2. layout使用的是match_parent，但父控件的size已经可以确定了，比如设置的是具体的值或者match_parent
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize; //建议：result直接使用确定值
        }
        //1. layout使用的是wrap_content
        //2. layout使用的是match_parent,但父控件使用的是确定的值或者wrap_content
        else if (specMode == MeasureSpec.AT_MOST) {
            result = Math.min(defaultSize, specSize); //建议：result不能大于specSize
        }
        //UNSPECIFIED,没有任何限制，所以可以设置任何大小
        //多半出现在自定义的父控件的情况下，期望由自控件自行决定大小
        else {
            result = defaultSize;
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置圆形画笔颜色
        mPaint.setColor(Color.BLUE);
        // FILL填充, STROKE描边,FILL_AND_STROKE填充和描边
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        //获取宽高
        int with = getWidth();
        int height = getHeight();
        float radius = with / 2;
        //绘制圆形
        canvas.drawCircle(with/2 , with/2 , radius, mPaint);
        //设置要绘制文字画笔颜色
        mPaint.setColor(Color.WHITE);
        //设置字号
        mPaint.setTextSize(30f);
        //要绘制的文字
        String text="自定义控件";
        //拿到字符串的宽度
        float stringWidth = mPaint.measureText(text);
        //根据宽度计算位置
        float x =with/2-stringWidth/2;
        canvas.drawText("自定义控件",x,height/2,mPaint);
    }
}
